// Token存储的键
const TOKEN_STORE_KEY = "authToken";
// RefreshToken存储的键
const REFRESH_TOKEN_STORE_KEY = "refreshToken";

/**
 * Token管理类 - Web版本
 * @author BelovedLYC (改编自FlanChan的RN版本)
 */
class TokenManager {
  private token: string | null = null;
  private refreshToken: string | null = null;

  /**
   * 构造函数：当对象初始化时自动获取本地中的token
   */
  constructor() {
    this.loadTokens();
  }

  /**
   * 从localStorage加载tokens
   */
  private loadTokens(): void {
    try {
      this.token = localStorage.getItem(TOKEN_STORE_KEY);
      this.refreshToken = localStorage.getItem(REFRESH_TOKEN_STORE_KEY);
    } catch (error) {
      console.error("加载token失败:", error);
    }
  }

  /**
   * 设置token
   * @param token JWT
   */
  setToken(token: string): void {
    localStorage.setItem(TOKEN_STORE_KEY, token);
    this.token = token;
  }

  /**
   * 设置refreshToken
   * @param refreshToken
   */
  setRefreshToken(refreshToken: string): void {
    localStorage.setItem(REFRESH_TOKEN_STORE_KEY, refreshToken);
    this.refreshToken = refreshToken;
  }

  /**
   * 获取token
   */
  getToken(): string | null {
    return this.token;
  }

  /**
   * 获取refreshToken
   */
  getRefreshToken(): string | null {
    return this.refreshToken;
  }

  /**
   * 清除token
   */
  clearToken(): void {
    this.token = null;
    localStorage.removeItem(TOKEN_STORE_KEY);
  }

  /**
   * 清除refreshToken
   */
  clearRefreshToken(): void {
    this.refreshToken = null;
    localStorage.removeItem(REFRESH_TOKEN_STORE_KEY);
  }

  /**
   * 清除所有token
   */
  clearAllTokens(): void {
    this.clearToken();
    this.clearRefreshToken();
  }
}

// 返回一个TokenManager实例以供使用
export default new TokenManager();
